package com.api.shopapi.util;

import com.api.shopapi.config.WxBarcodePayConfig;
import com.api.shopapi.config.WxConfig;
import com.api.shopapi.controller.BaseController;
import com.api.shopapi.util.wxutil.WXPay;
import com.api.shopapi.util.wxutil.WXPayConstants;
import com.api.shopapi.util.wxutil.WXPayUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

import static com.api.shopapi.util.wxutil.WXPayUtil.generateNonceStr;


@Slf4j
public class WechatPayUtils extends BaseController {



    //App支付
    public static Map appOrders(String ip, String orderNumber, double totalAmount,String notifyUrl) throws Exception {

        WxConfig wxConfig = new WxConfig();

        WXPay wxPay = new WXPay(wxConfig, WXPayConstants.SignType.MD5);

//        String notifyUrl = thisUrl+":"+port+"/PayNotify/WxPayNotify";
        log.info("wxPayNotifyUrl:"+notifyUrl);

        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("appid", wxConfig.getAppID());
        paraMap.put("body", "乐庭关爱");
        paraMap.put("mch_id", wxConfig.getMchID());
        paraMap.put("nonce_str", generateNonceStr());
        paraMap.put("out_trade_no", orderNumber);//订单号
        paraMap.put("spbill_create_ip", ip);
        String money = totalAmount * 100 + "";
        paraMap.put("total_fee", money.split("\\.")[0]);
        paraMap.put("trade_type", "APP");
        paraMap.put("notify_url", notifyUrl);// 此路径是微信服务器调用支付结果通知路径随意写
        String sign = WXPayUtil.generateSignature(paraMap, wxConfig.getKey());
        paraMap.put("sign", sign);

        Map<String, String> respData = wxPay.unifiedOrder(paraMap);
        Map<String, String> payMap = new HashMap<>();
        if (respData.get("return_code").equals("SUCCESS")) {

            //返回给APP端的参数，APP端再调起支付接口

            payMap.put("appid", respData.get("appid"));
            payMap.put("partnerid", wxConfig.getMchID());
            payMap.put("prepayid", respData.get("prepay_id"));
            payMap.put("package", "Sign=WXPay");
            payMap.put("noncestr", generateNonceStr());
            payMap.put("timestamp", WXPayUtil.getCurrentTimestamp() + "");
            String paySign = WXPayUtil.generateSignature(payMap, wxConfig.getKey());
            payMap.put("sign", paySign);
        } else {
            paraMap.put("fail", "下单失败");
            paraMap.put("return_msg", respData.get("return_msg"));
        }
        return payMap;
    }

    //App支付退款
    public static Map<String, String> wechatRefund(String orderNo, double totalAmount, double refundAmount, String out_refund_no) throws Exception {

        WxConfig wxConfig = new WxConfig();

        WXPay wxPay = new WXPay(wxConfig);

        String nonceStr = generateNonceStr();
        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("appid", wxConfig.getAppID());
        paraMap.put("mch_id", wxConfig.getMchID());
        paraMap.put("nonce_str", nonceStr);
        paraMap.put("out_trade_no", orderNo);
        paraMap.put("out_refund_no", out_refund_no);
        String totalMoney = totalAmount * 100 + "";
        paraMap.put("total_fee", totalMoney.split("\\.")[0]);
        String refundMoney = refundAmount * 100 + "";
        paraMap.put("refund_fee", refundMoney.split("\\.")[0]);
        paraMap.put("refund_desc", "退款订单");
        String sign = WXPayUtil.generateSignature(paraMap, wxConfig.getKey());
        paraMap.put("sign", sign);

        Map<String, String> refundMap = wxPay.refund(paraMap);
        Map<String, String> resultMap = new HashMap<String, String>();
        if (refundMap.get("return_code").equals("SUCCESS") && refundMap.get("result_code").equals("SUCCESS")) {
            resultMap.put("refundType", "success");
            resultMap.put("msg", "微信退款成功");
        } else {
            resultMap.put("refundType", "fail");
            resultMap.put("msg", "微信退款失败:" + refundMap.get("return_msg"));
        }
        return resultMap;
    }


    /**
     * 微信条码支付
     * @param orderNumber 订单编号
     * @param totalAmount 订单金额（元）
     * @param authCode 用户微信付款码
     * @return
     * @throws Exception
     */
    public static Map barcodePay(String authCode,String orderNumber, double totalAmount) throws Exception {

        WxBarcodePayConfig wxConfig=new WxBarcodePayConfig();

        WXPay wxPay = new WXPay(wxConfig, WXPayConstants.SignType.MD5);


        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("appid", wxConfig.getAppID());
        paraMap.put("body", wxConfig.getBody());
        paraMap.put("mch_id", wxConfig.getMchID());
        paraMap.put("nonce_str", generateNonceStr());
        paraMap.put("out_trade_no", orderNumber);//订单号
        paraMap.put("spbill_create_ip", wxConfig.getSpbill_create_ip());
        String money = totalAmount * 100 + "";
        paraMap.put("total_fee", money.split("\\.")[0]);
        paraMap.put("auth_code",authCode);
        String sign = WXPayUtil.generateSignature(paraMap, wxConfig.getKey());
        paraMap.put("sign", sign);

        Map<String, String> respData = wxPay.microPay(paraMap);
        Map<String, String> payMap = new HashMap<>();

        System.out.println(respData.toString());


        if (respData.get("return_code").equals("SUCCESS")) {
            if (respData.get("result_code").equals("SUCCESS")){
                paraMap.put("success", "支付成功");
            }

            payMap.put("tag","ok");
        } else {
            paraMap.put("fail", "支付失败");
            paraMap.put("return_msg", respData.get("return_msg"));

            payMap.put("tag","fail");
        }
        return payMap;
    }




}
